import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/plan.dart';
import 'package:awak/common/routers/router_names.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class MyPlanPage extends StatefulWidget {
  const MyPlanPage({super.key});

  @override
  State<MyPlanPage> createState() => _MyPlanPageState();
}

class _MyPlanPageState extends State<MyPlanPage> {
  int _selectedMonth = DateTime.now().month;
  int _selectedYear = DateTime.now().year;
  DateTime _selectedDate = DateTime.now();
  int _selectedTabIndex = 0;

  List<Plan> _uncompletedPlans = [];
  List<Plan> _completedPlans = [];
  List<Plan> _failedPlans = [];

  final PageController _datePageController = PageController(
    initialPage: DateTime.now().day - 1,
    viewportFraction: 0.2,
  );

  @override
  void initState() {
    super.initState();
    _loadPlansForSelectedDate();
  }

  @override
  void dispose() {
    _datePageController.dispose();
    super.dispose();
  }

  void _loadPlansForSelectedDate() {
    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
    if (currentUser != null) {
      // 首先更新超时的计划状态
      context.read<AwakBloc>().add(UpdateExpiredPlansEvent(currentUser.id!));
      // 然后加载最近30天的计划
      context.read<AwakBloc>().add(FetchLast30DaysPlansEvent(currentUser.id!));
    }
  }

  List<Plan> _filterPlansByDate(List<Plan> allPlans) {
    final selectedDay = DateTime(_selectedDate.year, _selectedDate.month, _selectedDate.day);
    final selectedDayEnd = selectedDay.add(Duration(days: 1));

    return allPlans.where((plan) {
      // 检查计划是否与选中的日期有重叠
      // 计划开始时间 < 选中日期结束 && 计划结束时间 > 选中日期开始
      return plan.startTime.isBefore(selectedDayEnd) && plan.endTime.isAfter(selectedDay);
    }).toList();
  }

  String _getMonthName(int month) {
    const months = [
      'January', 'February', 'March', 'April', 'May', 'June',
      'July', 'August', 'September', 'October', 'November', 'December'
    ];
    return months[month - 1];
  }

  String _getWeekdayName(int weekday) {
    const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    return weekdays[weekday - 1];
  }

  int _getDaysInMonth(int year, int month) {
    return DateTime(year, month + 1, 0).day;
  }

  String _formatCountdown(DateTime endTime) {
    final now = DateTime.now();
    final difference = endTime.difference(now);

    if (difference.isNegative) {
      return '00:00:00';
    }

    final days = difference.inDays;
    final hours = difference.inHours % 24;
    final minutes = difference.inMinutes % 60;
    final seconds = difference.inSeconds % 60;

    if (days > 0) {
      return '${days}d ${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    } else {
      return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
    }
  }

  @override
  Widget build(BuildContext context) {
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        if (state is Last30DaysPlansLoaded) {
          final filteredPlans = _filterPlansByDate(state.plans);
          setState(() {
            _uncompletedPlans = filteredPlans.where((plan) => plan.state == 'uncompleted').toList();
            _completedPlans = filteredPlans.where((plan) => plan.state == 'completed').toList();
            _failedPlans = filteredPlans.where((plan) => plan.state == 'failed').toList();
          });
        } else if (state is ExpiredPlansUpdated) {
          // 超时计划更新后，重新加载计划列表
          _loadPlansForSelectedDate();
        }
      },
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFD7F349),
              Color(0xFFFFFABA),
            ],
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          body: SafeArea(
            child: Column(
              children: [
                // 上半部分
                _buildUpperSection(),
                // 下半部分
                Expanded(
                  child: _buildLowerSection(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildUpperSection() {
    return Container(
      margin: EdgeInsets.all(20.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Color(0xFFFAFFDF),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(14.r),
          bottomRight: Radius.circular(14.r),
        ),
      ),
      child: Column(
        children: [
          // 标题栏
          Row(
            children: [
              GestureDetector(
                onTap: () => Beamer.of(context).beamBack(),
                child: Icon(AwakSvg.back, size: 20.w, color: Colors.black),
              ),
              Expanded(
                child: Center(
                  child: Text(
                    'MY PLAN',
                    style: AwakText.titleStyle
                  ),
                ),
              ),
              SizedBox(width: 24.w),
            ],
          ),
          SizedBox(height: 20.h),
          // 月份选择
          _buildMonthSelector(),
          SizedBox(height: 16.h),
          // 分割线
          Container(
            height: 1.h,
            color: Colors.grey.withValues(alpha: 0.3),
          ),
          SizedBox(height: 16.h),
          // 日期选择
          _buildDateSelector(),
        ],
      ),
    );
  }

  Widget _buildMonthSelector() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: List.generate(12, (index) {
          final month = index + 1;
          final isSelected = month == _selectedMonth;
          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedMonth = month;
                _selectedDate = DateTime(_selectedYear, _selectedMonth, 1);
              });
              _loadPlansForSelectedDate();
            },
            child: Container(
              margin: EdgeInsets.only(right: 12.w),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              decoration: BoxDecoration(
                color: isSelected ? Color(0xFFF5FFBF) : Colors.transparent,
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Text(
                _getMonthName(month),
                style: AwakText.body14Style.copyWith(
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                  color: Colors.black,
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  Widget _buildDateSelector() {
    final daysInMonth = _getDaysInMonth(_selectedYear, _selectedMonth);
    final today = DateTime.now();

    return Container(
      height: 80.h,
      child: PageView.builder(
        controller: _datePageController,
        itemCount: daysInMonth,
        onPageChanged: (index) {
          setState(() {
            _selectedDate = DateTime(_selectedYear, _selectedMonth, index + 1);
          });
          _loadPlansForSelectedDate();
        },
        itemBuilder: (context, index) {
          final date = DateTime(_selectedYear, _selectedMonth, index + 1);
          final isToday = date.day == today.day &&
                         date.month == today.month &&
                         date.year == today.year;
          final isSelected = date.day == _selectedDate.day;

          return GestureDetector(
            onTap: () {
              setState(() {
                _selectedDate = date;
              });
              _loadPlansForSelectedDate();
            },
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 4.w),
              decoration: BoxDecoration(
                color: isSelected ? Color(0xFFB6F558) :
                       isToday ? Color(0xFF8FE344) : Color(0xFFF5FFBF),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '${date.day}',
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      fontSize: 16.sp,
                      color: Colors.black,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    _getWeekdayName(date.weekday),
                    style: AwakText.body14Style.copyWith(
                      fontSize: 12.sp,
                      color: Colors.black.withValues(alpha: 0.7),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildLowerSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          // 标签栏
          _buildTabBar(),
          SizedBox(height: 16.h),
          // 计划列表
          Expanded(
            child: _buildPlanList(),
          ),
        ],
      ),
    );
  }

  Widget _buildTabBar() {
    final tabs = ['Uncompleted Plan', 'Completed Plan', 'Failed Plan'];

    return Row(
      children: List.generate(tabs.length, (index) {
        final isSelected = index == _selectedTabIndex;
        return Expanded(
          child: GestureDetector(
            onTap: () {
              setState(() {
                _selectedTabIndex = index;
              });
            },
            child: Container(
              padding: EdgeInsets.symmetric(vertical: 12.h),
              child: Center(
                child: Text(
                  tabs[index],
                  style: AwakText.body14Style.copyWith(
                    fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                    color: isSelected ? Colors.black : Colors.grey[600],
                    fontSize: 13.sp,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
            ),
          ),
        );
      }),
    );
  }

  Widget _buildPlanList() {
    List<Plan> currentPlans;
    switch (_selectedTabIndex) {
      case 0:
        currentPlans = _uncompletedPlans;
        break;
      case 1:
        currentPlans = _completedPlans;
        break;
      case 2:
        currentPlans = _failedPlans;
        break;
      default:
        currentPlans = [];
    }

    if (currentPlans.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              AwakImages.empty,
              width: 120.w,
              height: 120.h,
            ),
            SizedBox(height: 20.h),
            Text(
              'No plans found',
              style: AwakText.body14Style.copyWith(
                color: Colors.grey,
                fontSize: 16.sp,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              'Try selecting a different date',
              style: AwakText.body14Style.copyWith(
                color: Colors.grey.withValues(alpha: 0.7),
                fontSize: 14.sp,
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      itemCount: currentPlans.length,
      itemBuilder: (context, index) {
        final plan = currentPlans[index];
        return GestureDetector(
          onTap: () {
            Beamer.of(context).beamToNamed(
              RouterNames.detailPlan,
              data: plan,
            );
          },
          child: _buildPlanCard(plan),
        );
      },
    );
  }

  Widget _buildPlanCard(Plan plan) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Color(0xFFFCFFED),
        borderRadius: BorderRadius.circular(20.r),
      ),
      child: Row(
        children: [
          // 计划图片
          ClipRRect(
            borderRadius: BorderRadius.circular(12.r),
            child: Image.asset(
              plan.picture,
              width: 60.w,
              height: 60.w,
              fit: BoxFit.cover,
            ),
          ),
          SizedBox(width: 12.w),
          // 计划信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 标题行
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        plan.title,
                        style: AwakText.body14Style.copyWith(
                          fontWeight: FontWeight.w600,
                          fontSize: 16.sp,
                        ),
                      ),
                    ),
                    if (plan.state == 'completed')
                      Icon(Icons.check_circle, color: Colors.green, size: 20.w)
                    else if (plan.state == 'failed')
                      Icon(Icons.cancel, color: Colors.red, size: 20.w),
                  ],
                ),
                SizedBox(height: 8.h),
                // 描述
                Text(
                  plan.description,
                  style: AwakText.body14Style.copyWith(
                    color: Colors.grey[600],
                    fontSize: 12.sp,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(height: 12.h),
                // 底部信息
                _buildPlanCardBottom(plan),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPlanCardBottom(Plan plan) {
    if (plan.state == 'uncompleted') {
      return Row(
        children: [
          Icon(Icons.access_time, size: 16.w, color: Colors.grey[600]),
          SizedBox(width: 4.w),
          Text(
            'Count Down',
            style: AwakText.body14Style.copyWith(
              fontSize: 12.sp,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(width: 8.w),
          Text(
            _formatCountdown(plan.endTime),
            style: AwakText.body14Style.copyWith(
              fontSize: 12.sp,
              fontWeight: FontWeight.w600,
              color: Colors.black,
            ),
          ),
        ],
      );
    } else if (plan.state == 'completed') {
      return Row(
        children: [
          Icon(Icons.check_circle, size: 16.w, color: Colors.green),
          SizedBox(width: 4.w),
          Text(
            'Completed',
            style: AwakText.body14Style.copyWith(
              fontSize: 12.sp,
              color: Colors.green,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      );
    } else {
      return Row(
        children: [
          Icon(Icons.cancel, size: 16.w, color: Colors.red),
          SizedBox(width: 4.w),
          Text(
            'Uncompleted',
            style: AwakText.body14Style.copyWith(
              fontSize: 12.sp,
              color: Colors.red,
              fontWeight: FontWeight.w600,
            ),
          ),
        ],
      );
    }
  }
}